﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace CIS.Client.Common.HttpRequestHelper
{
    /// <summary>
    /// 调用Api 工具类
    /// </summary>
    public class HttpRequestClient
    {
        public static HttpClient Client = new HttpClient();

        /// <summary>
        /// 请求地址的公共部分
        /// </summary>
        private readonly string baseUrl = "https://localhost:5000/";


        /// <summary>
        /// Http Get请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns>返回数据</returns>
        public async Task<RequestResult> SendGetAsync(HttpRequest httpRequest)
        {
            RestRequest request = new RestRequest();
            try
            {
                request.AddHeader("ContentType", httpRequest.ContentType);
                var url = new Uri(baseUrl + httpRequest.Route);
                var response = await Client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    string resultContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<RequestResult>(resultContent);
                }
                else
                {
                    return new RequestResult { StatusCode = response.StatusCode, Message = "服务器忙，请稍后" };
                }
            }
            catch 
            {
                return new RequestResult { StatusCode = HttpStatusCode.NotFound, Message = "服务器忙，请稍后" };
            }
        }

        /// <summary>
        /// Http Post 请求
        /// </summary>
        /// <param name="httpRequest">请求参数</param>
        /// <returns>返回数据</returns>
        public async Task<RequestResult> SendPostAsync(HttpRequest httpRequest)
        {
            RestRequest request = new RestRequest();
            try
            {
                request.AddHeader("ContentType", httpRequest.ContentType);
                var url = new Uri(baseUrl + httpRequest.Route);
                var response = await Client.PostAsJsonAsync(url, httpRequest.Parameters);
                if (response.IsSuccessStatusCode)
                {
                    string resultContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<RequestResult>(resultContent);
                }
                else
                {
                    return new RequestResult { StatusCode = response.StatusCode, Message = "服务器忙，请稍后" };
                }
            }
            catch
            {
                return new RequestResult { StatusCode = HttpStatusCode.NotFound, Message = "服务器忙，请稍后" };
            }
        }


    }
}
